package cn.xiazhi.charging.order.config;

import cn.xiazhi.charging.order.mqtt.MqttConsumer;
import cn.xiazhi.charging.order.mqtt.MqttContext;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Random;
@Slf4j
@Configuration
public class MqttConfiguration {
    @Autowired
    private MqttContext mqttContext;

    /**
     * 用户名
     * 这些配置信息 应该放到配置文件, 或者放到配置中心 nacos (注册中心和配置中心)
     */
    private String userName = "admin";

    /**
     * 密码
     */
    private String password = "public";

    /**
     * 连接地址 tcp协议 端口 1883
     * mysql jdbc://localhost:3306/databaseName
     */
    private String host = "tcp://localhost:1883";

    /**
     * 客户端 启动多个订单服务,需要保证每个订单服务的clientId 不同
     */
    private String clientId = "order_service_client" + getRandom();

    private int getRandom() {
        Random random = new Random();
        return random.nextInt(100);
    }

    @Bean
    public MqttClient getMqttConfig() throws MqttException {
        /**
         * 通过连接地址和clientId 进行连接
         */
        MqttClient mqttClient = new MqttClient(host, clientId);

        /**
         * 连接相关的配置
         */
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setUserName(userName);
        connOpts.setPassword(password.toCharArray());
        //清理会话session
        connOpts.setCleanSession(true);
        //自动重连
        connOpts.setAutomaticReconnect(true);
        //版本号设置
        connOpts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);

        //mqttConsumer 是通过new 的方式创建的,没有在spring容器里
        //MqttClient 是通过@Bean的方式 创建的,在spring容器里
        //没有在spring容器里的mqttConsumer 想使用 在spring容器里 MqttClient
        MqttConsumer mqttConsumer = new MqttConsumer();
        mqttConsumer.setMqttClient(mqttClient);
        mqttConsumer.setMqttContext(mqttContext);

        //设置回调类
        mqttClient.setCallback(mqttConsumer);

        //connect mqttClient的连接方法,基于配置 connOpts 和 EMQX 进行连接
        mqttClient.connect(connOpts);
        log.debug("MqttConfiguration#mqttClient,设置了回调类后,和EMQX进行连接");

        return mqttClient;

    }

}

















